import json
import subprocess


class Script:
    TYPE = ''

    def __init__(self, script, variables):
        self.script = script
        self.variables = variables

    def execute(self):
        pass


class PyScript(Script):
    TYPE = 'Python'

    def __init__(self, script, variables):
        super().__init__(script=script, variables=variables)

    def execute(self):
        """python脚本执行"""
        exec(self.script, self.variables)
        return 0


class ShScript(Script):
    TYPE = 'Shell'

    def __init__(self, script, variables):
        super().__init__(script=script, variables=variables)

    def execute(self):
        variable_str = '\n'.join([f'{k}={v}' for k, v in self.variables.items()])
        script = '\n'.join([variable_str, self.script])
        resp = subprocess.run(['sh', '-c', script], capture_output=True, text=True)
        if resp.returncode == 0:
            return 0
        raise Exception(resp.stderr)


class PerlScript(Script):
    TYPE = 'Perl'

    def __init__(self, script, variables):
        super().__init__(script=script, variables=variables)

    def execute(self):
        """perl"""
        variable_str = '\n'.join([f'${k}={json.dumps(v, ensure_ascii=False)};' for k, v in self.variables.items()])
        script = '\n'.join([variable_str, self.script])
        resp = subprocess.run(['perl', '-e', script], capture_output=True, text=True)
        if resp.returncode == 0:
            return 0
        raise Exception(resp.stderr)


script_map = {item.TYPE: item for item in Script.__subclasses__()}

if __name__ == '__main__':
    code_1 = PyScript('print(a)', variables={'a': 1}).execute()
    code_2 = ShScript('echo ${a}', variables={'a': 'ee'}).execute()
    code_3 = PerlScript("""
    print "Enter your name: ";
    print "Hello, ${name} ... you will soon be a Perl addict!";
    print "";""", variables={'name': 'b'}).execute()
    print(code_1, code_2, code_3)
